"""
Enhanced data objects for XtGateway to support advanced xtdata features.

This module extends VNPy's basic subscription capabilities to fully leverage
xtquant's powerful data subscription features including:
- Multiple periods (tick, 1m, 5m, 1d, etc.)
- Dividend adjustments (front/back/none)
- L2 thousand-level market depth
- Whole market quote subscription
"""

from dataclasses import dataclass
from typing import Optional, Callable, Any
from vnpy.trader.object import SubscribeRequest
from vnpy.trader.constant import Exchange


@dataclass
class XtSubscribeRequest(SubscribeRequest):
    """
    Extended subscription request for XtGateway.
    
    Adds support for:
    - period: Data period (tick, 1m, 5m, 15m, 30m, 60m, 1d, 1w, etc.)
    - dividend_type: Dividend adjustment type (none, front, back, front_ratio, back_ratio)
    - start_time: Start time for historical data subscription
    - end_time: End time for historical data subscription
    - count: Number of data points to retrieve (-1 for all)
    """
    
    period: str = "tick"  # Default to tick for compatibility
    dividend_type: Optional[str] = None  # None, "none", "front", "back", "front_ratio", "back_ratio"
    start_time: str = ""  # YYYYMMDD or YYYYMMDDhhmmss
    end_time: str = ""  # YYYYMMDD or YYYYMMDDhhmmss
    count: int = 0  # Number of bars, 0 means real-time only, -1 means all
    
    def __post_init__(self):
        """Validate parameters"""
        super().__post_init__()
        
        # Validate period
        valid_periods = [
            "tick", 
            "1m", "5m", "15m", "30m", "60m",  # Minutes
            "1d", "1w", "1mon", "1q", "1hy", "1y"  # Days and above
        ]
        if self.period not in valid_periods:
            raise ValueError(f"Invalid period: {self.period}. Must be one of {valid_periods}")
        
        # Validate dividend_type
        if self.dividend_type is not None:
            valid_dividend_types = ["none", "front", "back", "front_ratio", "back_ratio"]
            if self.dividend_type not in valid_dividend_types:
                raise ValueError(f"Invalid dividend_type: {self.dividend_type}. Must be one of {valid_dividend_types}")


@dataclass
class XtL2SubscribeRequest:
    """
    L2 thousand-level market depth subscription request.
    
    Supports:
    - Basic thousand-level quotes
    - Queue data at specific price levels or gears
    """
    
    symbol: str
    exchange: Exchange
    gear_num: Optional[int] = None  # Number of gears to subscribe (None for all)
    callback: Optional[Callable] = None
    
    def __post_init__(self):
        """Generate vt_symbol"""
        self.vt_symbol: str = f"{self.symbol}.{self.exchange.value}"


@dataclass 
class XtWholeQuoteRequest:
    """
    Whole market quote subscription request.
    
    Subscribe to entire market or list of stocks for real-time quotes.
    """
    
    code_list: list[str]  # List of markets ["SH", "SZ"] or stocks ["600000.SH", "000001.SZ"]
    callback: Optional[Callable] = None


# Period mapping for different bar intervals
PERIOD_VT2XT: dict[str, str] = {
    "1m": "1m",
    "5m": "5m", 
    "15m": "15m",
    "30m": "30m",
    "60m": "60m",
    "1d": "1d",
    "1w": "1w",
    "tick": "tick"
}

# Dividend type descriptions for reference
DIVIDEND_TYPE_DESC: dict[str, str] = {
    "none": "不复权 - No adjustment",
    "front": "前复权 - Forward adjustment", 
    "back": "后复权 - Backward adjustment",
    "front_ratio": "前复权比例 - Forward ratio adjustment",
    "back_ratio": "后复权比例 - Backward ratio adjustment"
}
